package com.service;

import com.alibaba.fastjson.JSON;
import com.entity.FeiPin_wzl;
import com.entity.Stage_wzl;
import com.utils.EntityFactory;
import com.utils.ExecUtil;
import com.utils.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/feipin/query", "/feipin/edit"})
public class FeiPinService_wzl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!req.getServletPath().equals("/feipin/query")) {
            resp.getWriter().write("403 not allowed");
            return;
        }
        String sql = "select * from feipin_wzl";
        List<FeiPin_wzl> feiPinWzlList = new ArrayList<>();
        List<Object> params = new ArrayList<>();
        try (ResultSet resultSet = (ResultSet) ExecUtil.execute(sql, params, req, false)) {
            while (resultSet.next()) {
                EntityFactory entityFactory = new EntityFactory<>(FeiPin_wzl.class);
                FeiPin_wzl feiPin_wzl = (FeiPin_wzl) entityFactory.startCombine(resultSet);
                feiPinWzlList.add(feiPin_wzl);
            }
            resp.getWriter().write(JSON.toJSONString(feiPinWzlList));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                ExecUtil.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sql;
        List<Object> params = new ArrayList<>();
        String data;
        if (req.getServletPath().equals("/feipin/edit")) {
            sql = "update feipin_wzl set zhi=?,ping=?";
            params.add(req.getParameter("zhi"));
            params.add(req.getParameter("ping"));
            data = "编辑成功";
            try {
                ExecUtil.execute(sql, params, req, true);
                resp.getWriter().write(Result.success(data));
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    ExecUtil.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
